package com.fling.abcde.ui.citypicker;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.fling.abcde.R;
import com.fling.abcde.base.BaseActivity;
import com.fling.abcde.ui.citypicker.adapter.CityListAdapter;
import com.fling.abcde.ui.citypicker.adapter.ResultListAdapter;
import com.fling.abcde.ui.citypicker.db.DBManager;
import com.fling.abcde.ui.citypicker.model.City;
import com.lib.utils.SPUtils;
import com.lib.common.view.ClearEditText;
import com.lib.common.view.RightNavView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class CityPickerActivity extends BaseActivity {

    public static final int LOCATING = 0x2;
    public static final int FAILED = 0x22;
    public static final int SUCCESS = 0x44;

    private ListView mListView;
    private ListView mResultListView;
    private ClearEditText mClearEditText;
    private TextView emptyView;

    private CityListAdapter mCityAdapter;
    private ResultListAdapter mResultAdapter;
    private DBManager mDBManager;
    private String mCity = "";
    private InnerHandler mHandler = new InnerHandler(this);

    private static class InnerHandler extends Handler {

        private final CityPickerActivity mActivity;

        InnerHandler(CityPickerActivity activity) {

            mActivity = new WeakReference<>(activity).get();
        }

        @Override
        public void handleMessage(Message msg) {

            mActivity.initLocation();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setTitle("城市定位");
        setContentView(R.layout.activity_locate_city);
        initData();
        initView();
        initLocation();
    }

    private void initLocation() {

        SharedPreferences sp = SPUtils.getSP();
        String city = sp.getString(SPUtils.KEY_LOCATED_CITY, null);
        String district = sp.getString(SPUtils.KEY_LOCATED_DISTRICT, null);

        if (city == null || district == null) {
            //定位失败
            mCityAdapter.updateLocateState(FAILED, null);
            return;
        }
        mCityAdapter.updateLocateState(SUCCESS, city);
    }

    private void initData() {

        mDBManager = new DBManager(this);
        mDBManager.copyDBFile();
        ArrayList<City> allCities = mDBManager.getAllCities();
        mCityAdapter = new CityListAdapter(allCities);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {

            @Override
            public void onCityClick(String name) {

                setResult(name);
            }

            @Override
            public void onLocateClick() {

                mCityAdapter.updateLocateState(LOCATING, null);
                // LocationInfoManager.start();
                mHandler.sendEmptyMessageDelayed(0, 2000);

            }
        });
        mResultAdapter = new ResultListAdapter(this, null);
    }

    private void initView() {

        mListView = findViewById(R.id.listview_all_city);
        mListView.setAdapter(mCityAdapter);

        RightNavView rightNavView = findViewById(R.id.side_letter_bar);
        rightNavView.setOnItemSelectedListener(new RightNavView.OnItemSelectedListener() {

            @Override
            public void onItemSelecting(int index, String indexStr) {

                if (index <= 1) {
                    mListView.setSelection(index);
                } else {
                    int position = mCityAdapter.getLetterPosition(indexStr);
                    mListView.setSelection(position);
                }
            }

            @Override
            public void onItemSelected(int index, String indexStr) {

            }
        });
        mClearEditText = (ClearEditText) findViewById(R.id.et_search);
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                String keyword = s.toString();
                if (TextUtils.isEmpty(keyword)) {
                    emptyView.setVisibility(View.GONE);
                    mResultListView.setVisibility(View.GONE);
                } else {
                    mResultListView.setVisibility(View.VISIBLE);
                    List<City> result = mDBManager.searchCity(keyword);
                    if (result == null || result.size() == 0) {
                        emptyView.setVisibility(View.VISIBLE);
                    } else {
                        emptyView.setVisibility(View.GONE);
                        mResultAdapter.changeData(result);
                    }
                }
            }
        });

        emptyView = (TextView) findViewById(R.id.empty_view);
        mResultListView = (ListView) findViewById(R.id.listview_search_result);
        mResultListView.setAdapter(mResultAdapter);
        mResultListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                setResult(mResultAdapter.getItem(position).getName());
            }
        });
    }

    private void setResult(final String city) {

        // if (mAlertDialog == null) {
        // 	mAlertDialog = new AlertDialog.Builder(this)
        // 		.setMessage("一次VIP只有一次切换机会，是否切换至" + city + "？")
        // 		.setPositiveButton("确定切换", new DialogInterface.OnClickListener() {
        //
        // 			@Override
        // 			public void onClick(DialogInterface dialog, int which) {

        mCity = city;
        onBackPressed();
        // 			}
        // 		}).setNegativeButton("再看看先", null)
        // 		.create();
        // }
        // mAlertDialog.show();
    }

    @Override
    public void onBackPressed() {

        if (mCity.equals("")) {
            mCity = mCityAdapter.getLocated();
            if (mCity.contains("定位")) {
                mCity = "定位...";
            }
        }
        Intent data = new Intent(mCity);
        setResult(RESULT_OK, data);
        super.onBackPressed();
    }

    @Override
    protected void onPause() {

        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {

        mHandler = null;
        super.onDestroy();
    }
}